package com.meishij.fragment;


import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.chanven.lib.cptr.PtrUIHandler;
import com.chanven.lib.cptr.indicator.PtrIndicator;
import com.meishij.R;
import com.meishij.adapter.MallBodyAdapter;
import com.meishij.adapter.MallCategoryAdapter;
import com.meishij.adapter.MallViewPagerAdapter;
import com.meishij.entry.MallEntry;
import com.meishij.server.MallServer;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * A simple {@link Fragment} subclass.
 */
public class MallFragment extends Fragment implements Callback<MallEntry>, View.OnClickListener {

    private static final int current = 0;
    private TextView mall_search_text;
    private RecyclerView mall_main_body;
    private List<Object> list;
    private MallBodyAdapter mallBodyAdapter;
    private GridLayoutManager gridLayoutManager;
    private final String source = "android";
    private final String format = "json";
    private View view;
    private ImageView mall_back_to_header;
    private RelativeLayout mall;
    private PtrClassicFrameLayout ptr_mall_main;
    private Retrofit retrofit;
    private ImageView iv_ptr;
    private TextView tv_ptr_notify;
    private TextView tv_ptr_time;
    private View pullToHeadView;
    private int page=1;
    private boolean isFirst = true;
    private boolean canPullToRefresh = false;
    private boolean addMoreEndList;
    private ImageView mine_icon;
    private ImageView mall_shop_car;
    private ImageView mall_message_icon;
    private View inflateView;
    private PopupWindow popupWindow;

    public MallFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view != null) {
            return view;
        }
        view = inflater.inflate(R.layout.fragment_mall, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        if (mallBodyAdapter != null) {
            return;
        }
        mall_back_to_header = ((ImageView) view.findViewById(R.id.mall_back_to_header));
        mall = ((RelativeLayout) view.findViewById(R.id.mall));
        mall_back_to_header.setOnClickListener(this);
        mall_search_text = (TextView) view.findViewById(R.id.mall_search_text);
        //出popupmenu
        mine_icon = ((ImageView) view.findViewById(R.id.mine_icon));
        mine_icon.setOnClickListener(this);
        mall_shop_car = ((ImageView) view.findViewById(R.id.mall_shop_car));
        mall_shop_car.setOnClickListener(this);
        mall_message_icon = ((ImageView) view.findViewById(R.id.mall_message_icon));
        mall_message_icon.setOnClickListener(this);
        mall_main_body = ((RecyclerView) view.findViewById(R.id.mall_main_body));
        gridLayoutManager = new GridLayoutManager(getContext(), 1);
        mall_main_body.setLayoutManager(gridLayoutManager);
        mall_main_body.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) {//向上滑动
                    mall_back_to_header.setVisibility(View.INVISIBLE);
                    if(mall_main_body.canScrollVertically(1)==false){
                       // Toast.makeText(getContext(), "已拉到最低,正在加载数据", Toast.LENGTH_SHORT).show();
                        //现在要加载最下方end_List的新数据了
                        addMoreEndList=true;
                        page++;
                        //http://api.meishi.cc/v5/buy_index1.php?format=json
                        Retrofit build = new Retrofit.Builder().baseUrl("http://api.meishi.cc").addConverterFactory(GsonConverterFactory.create()).build();
                        Call<MallEntry> mall = build.create(MallServer.class).getMall(source, format, null, null, Integer.toString(page));
                        mall.enqueue(MallFragment.this);
                    }
                } else {//向下滑动,在这里加上拉加载更多
                    mall_back_to_header.setVisibility(View.VISIBLE);
                }

            }
        });
        ptr_mall_main = ((PtrClassicFrameLayout) view.findViewById(R.id.ptr_mall_main));
        setPtr();
        initRetrofit();
        getNetData();
    }

    private void setPtr() {
        pullToHeadView = LayoutInflater.from(getContext()).inflate(R.layout.item_shihua_anim_ptr, null);
        iv_ptr = ((ImageView) pullToHeadView.findViewById(R.id.iv_shihua_top_anim));
        tv_ptr_notify = ((TextView) pullToHeadView.findViewById(R.id.tv_shihua_top_notify));
        tv_ptr_time = ((TextView) pullToHeadView.findViewById(R.id.tv_shihua_top_time));
        ptr_mall_main.setHeaderView(pullToHeadView);
        //设置阻尼的效果
        ptr_mall_main.setResistance(2.0f);
        ptr_mall_main.setRatioOfHeaderHeightToRefresh(1.2f);
        //距离多少的时候就可以关闭
        ptr_mall_main.setDurationToClose(200);
        ptr_mall_main.setDurationToCloseHeader(1000);
        ptr_mall_main.addPtrUIHandler(new PtrUIHandler() {
            private AnimationDrawable animationDrawable;

            @Override
            public void onUIReset(PtrFrameLayout frame) {
                if (animationDrawable != null) {
                    animationDrawable.stop();
                }
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                animationDrawable = (AnimationDrawable) iv_ptr.getDrawable();
                //帧动画开始
                animationDrawable.start();
                tv_ptr_notify.setText("正在努力加载数据");
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    tv_ptr_notify.setText("刷新成功");
                    tv_ptr_time.setText("上次更新时间:" + new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()));
                }
                iv_ptr.setImageResource(R.drawable.anim_shihua_pull_to_refresh);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                //ptrFrameLayout的下拉距离
                int offsetToRefresh = frame.getOffsetToRefresh();
                //当前滑动到的Y位置
                int currentPosY = ptrIndicator.getCurrentPosY();
                //上一次滑动到的Y位置
                int lastPosY = ptrIndicator.getLastPosY();
                //向上滑或者下滑的距离 不到offsetToRefresh
                if (currentPosY < offsetToRefresh && lastPosY >= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("下拉刷新");
                    }
                }//到达一定下拉滑动距离
                else if (currentPosY > offsetToRefresh && lastPosY <= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("松开刷新");
                    }
                }
            }
        });
        ptr_mall_main.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if(canPullToRefresh){
                    Retrofit retrofit1 = new Retrofit.Builder().baseUrl("http://api.meishi.cc/")
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    Call<MallEntry> mallEntryCall = retrofit1.create(MallServer.class).getMall(source, format, null, null, null);
                    mallEntryCall.enqueue(MallFragment.this);
                    canPullToRefresh=false;
                    return;
                }else{
                    ptr_mall_main.refreshComplete();
                }
            }
        });
    }

    public void getNetData() {//这个是直接加载和下拉刷新时使用的网络请求
        if(ptr_mall_main!=null&&!ptr_mall_main.isRefreshing()&&!ptr_mall_main.isLoadingMore()){
            ptr_mall_main.autoRefresh();
        }
        Call<MallEntry> mallEntryCall = retrofit.create(MallServer.class).getMall(source, format, null, null, null);
        mallEntryCall.enqueue(this);
    }



    public void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl("http://api.meishi.cc")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Override
    public void onResponse(Call<MallEntry> call, Response<MallEntry> response) {
        MallEntry body = response.body();
        mall_search_text.setText(body.getBuy_sname());
        if (addMoreEndList){//如果是上拉加载更多的情况
            mallBodyAdapter.addEndList(body.getEnd_list());
        }else{
            if(isFirst){
                list=new ArrayList<>();
                list.add(0, body.getBuy_index_top());
                list.add(1, body.getCategory_infos());
                list.add(2, body.getAd_top());
                list.add(3, body.getZc());
                list.add(4, body.getEnd_list());
                mallBodyAdapter = new MallBodyAdapter(getContext(), list, new int[]{
                        R.layout.layout_mall_viewpager,
                        R.layout.layout_mall_category,
                        R.layout.layout_mall_ad_top,
                        R.layout.layout_mall_zc,
                        R.layout.layout_mall_end_list
                });
                mall_main_body.setAdapter(mallBodyAdapter);
            }else{
                mallBodyAdapter.remove(4);
                mallBodyAdapter.addNewData(4,body.getEnd_list());
                ptr_mall_main.refreshComplete();
            }
        }
        isFirst = false;
        canPullToRefresh = true;
        addMoreEndList=false;
    }

    @Override
    public void onFailure(Call<MallEntry> call, Throwable t) {
        Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
        t.printStackTrace();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mall_back_to_header:
                mall_main_body.scrollToPosition(0);
                break;
            case R.id.mine_icon:
                inflateView = getActivity().getLayoutInflater().inflate(R.layout.layout_mall_menu, null);
                popupWindow = new PopupWindow(inflateView,300,200,true);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                popupWindow.showAsDropDown(view);
                break;
            case R.id.mall_shop_car:

                break;
            case R.id.mall_message_icon:

                break;
        }
    }
}
